package com.mall.ums.interceptor;


import com.mall.model.domain.ums.Admin;
import com.mall.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求头
        String tokenStr = request.getHeader("Authorization");

        //2.解析token
        String[] tokenSplit = tokenStr.split(" ");
        String token = tokenSplit[1];
        boolean verifyToken = JwtUtils.verifyToken(token);
        //3.验证身份，判断是否放行
        if (!verifyToken) {
            response.setStatus(401);
            return false;
        } else {
            Claims claims = JwtUtils.getClaims(token);
            Integer id = (Integer) claims.get("id");
            String username = (String) claims.get("username");

            Admin admin = new Admin();
            admin.setId(id.longValue());
            admin.setUsername(username);

            AdminHolder.set(admin);

            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除
        AdminHolder.remove();
    }
}
